package com.manager.devicemanager.util;


import com.alibaba.fastjson2.JSONObject;
import com.aliyun.credentials.provider.EnvironmentVariableCredentialsProvider;
import com.aliyun.tea.TeaException;
import com.manager.devicemanager.vo.SmsParamVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public  class SmsUtils {
    private static final Logger logger = LoggerFactory.getLogger(SmsUtils.class);

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private  String templateCode;
    public  com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
//        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();

        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.setEndpoint("dysmsapi.aliyuncs.com");
         config.setAccessKeyId(accessKeyId);
         config.setAccessKeySecret(accessKeySecret);
        // --- 添加凭据关联 ---
        config.setCredential(credential); // 关联凭据客户端，自动读取环境变量
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";

        return new com.aliyun.dysmsapi20170525.Client(config);
    }
    public boolean sendSms(String phoneNumbers, SmsParamVO smsParamVO) {
        try {
//            System.out.println(smsParamVO.toString());
            com.aliyun.dysmsapi20170525.Client client = createClient();
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(phoneNumbers)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    // TemplateParam 为序列化后的 JSON 字符串。其中\"表示转义后的双引号。
//                    .setTemplateParam("{\"name\":\"张三\",\"number\":\"1390000****\"}");
                    .setTemplateParam("{\"device_name\":\""+smsParamVO.getDevice_name()+"\",\"message\":\""+smsParamVO.getMessage()+"\",\"time\":\""+smsParamVO.getTime()+"\"}");

            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.dysmsapi20170525.models.SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);

            // 根据返回结果判断短信是否发送成功
            if ("OK".equals(response.getBody().getCode())) {
                return true;
            } else {
                logger.error("短信发送失败，错误码: {}, 错误信息: {}", response.getBody().getCode(), response.getBody().getMessage());
                return false;
            }
        } catch (TeaException error) {
            logger.error("短信发送过程中发生 TeaException", error);
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("短信发送过程中发生未知异常", e);
            return false;
        }
    }

    public static void main(String[] args) {
        SmsUtils smsUtils = new SmsUtils();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "断电故障");
        jsonObject.put("time","2025-10-11 18:17:00");
        jsonObject.put("device_name", "设备");
        SmsParamVO smsParamVO = new SmsParamVO();
        smsParamVO.setMessage(jsonObject.getString("message"));
        smsParamVO.setTime(jsonObject.getString("time"));
        smsParamVO.setDevice_name("设备");
        smsUtils.sendSms("13572293694", smsParamVO);
    }
}
